import logging

from django.db.models.signals import post_save
from django.dispatch import receiver

from erp_system.models import MenuModel, PermissionsModel

logger = logging.getLogger('erp')
methods = {
    'POST': '新增',
    'DELETE': '删',
    'PUT': '改',
    'PATCH': '改局部',
    'GET': '查'
}


# sender：发送信号的人
# instance: 代表当前正在新增的menu对象
@receiver(post_save, sender=MenuModel)
def create_menus_permissions(sender, instance, created, **kwargs):
    """
    创建信号监控函数，信号接收者收到之后自动触发。创建菜单资源对应的权限
    """

    if created:
        logger.info('创建菜单资源对应的权限')
        if isinstance(instance, MenuModel):
            if not instance.parent:  # 没有父菜单，就是说menu是功能模块菜单对象（顶级菜单）
                permission = PermissionsModel.objects.create(name=instance.name + '的权限', is_menu=True)
                permission.menu = instance
                permission.save()
            else:  # 当前菜单是接口
                for method in methods.keys():
                    # permission = PermissionsModel.objects.create(name=f'{instance.name}的{methods.get("method")}的权限',
                    permission = PermissionsModel.objects.create(name=f'{methods.get(method)}',
                                                                 is_menu=False, method=method, path=instance.url,
                                                                 desc=f'{instance.name}的{methods.get(method)}的权限')
                    permission.menu = instance
                    permission.save()
        else:
            logger.warning('当前对象不是MenuModel类型，所以不需要创建对应的权限数据！')
